package com.example.Repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Repository.CommentRepository;
import com.example.dao.CommentDao;
import com.example.pojo.Comment;
import com.example.pojo.CommentLike;
import com.example.pojo.CommentRelation;
import com.example.pojo.Result;
import com.example.pojo.dto.CommentDto;
import com.example.pojo.vo.CommentVo;
import com.example.service.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author crt
 */
@EnableTransactionManagement
@Service
public class CommentRepositoryImpl implements CommentRepository {

    @Resource
    private CommentService commentService;
    @Resource
    private CommentRelationService commentRelationService;
    @Resource
    private CommentDao commentDao;
    @Resource
    private CommentLikeService commentLikeService;


    @Override
    @Transactional
    public Result<String> addComment(CommentDto commentDto) {
        try {
            //保存评论信息
            Comment comment = new Comment();
            comment.setUserId(commentDto.getUserId());
            comment.setTrendsId(commentDto.getTrendsId());
            comment.setCommentContent(commentDto.getCommentContent());
            comment.setCommentTime(new Date());
            commentService.save(comment);

            //保存评论关系
            List<CommentRelation> commentRelationList = new ArrayList<>();
            //有祖先的评论
            if(!ObjectUtils.isEmpty(commentDto.getCommentDto()) && !ObjectUtils.isEmpty(commentDto.getCommentDto().getCommentId())){
                //获取该评论的祖先
                List<Map<String,Integer>> fatherIdList = commentDao.fatherList(commentDto.getTrendsId(), commentDto.getCommentDto().getCommentId());
                //保存与祖先的关系
                for (Map<String,Integer> map : fatherIdList){
                    CommentRelation commentRelation = new CommentRelation();
                    commentRelation.setAncestor(map.get("id"));
                    commentRelation.setDescendant(comment.getId());
                    commentRelation.setDistance(map.get("distance")+1);
                    commentRelationList.add(commentRelation);
                }
            }else{
                //没有祖先的评论
                CommentRelation rootCommentRelation = new CommentRelation();
                rootCommentRelation.setAncestor(0);
                rootCommentRelation.setDescendant(comment.getId());
                rootCommentRelation.setDistance(1);
                commentRelationList.add(rootCommentRelation);
            }
            CommentRelation commentRelation = new CommentRelation();
            commentRelation.setAncestor(comment.getId());
            commentRelation.setDescendant(comment.getId());
            commentRelation.setDistance(0);
            commentRelationList.add(commentRelation);
            commentRelationService.saveBatch(commentRelationList);

            return Result.success("添加评论成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<List<CommentVo>> getCommentList(Integer trendsId) {

        //获取第一层评论
        List<CommentVo> commentVoList = commentDao.getFirstCommentList(trendsId);

        for (CommentVo commentVo : commentVoList){
            //通过第一层评论获取每个第一层评论的第二层评论
            List<CommentVo> subCommentList = commentDao.getSubCommentList(trendsId, commentVo.getCommentId());
            for (CommentVo commentVo1 : subCommentList){
                //获取第二层评论每个评论的祖先的用户名
                CommentVo commentVo2 = commentVoList.stream()
                        .filter(commentVo3 -> commentVo3.getCommentId().equals(commentVo1.getAncestor()))
                        .findFirst()
                        .orElse(null);
                if(ObjectUtils.isEmpty(commentVo2)){
                    commentVo2 = subCommentList.stream()
                            .filter(commentVo3 -> commentVo3.getCommentId().equals(commentVo1.getAncestor()))
                            .findFirst()
                            .orElse(null);
                }
                //将祖先用户名赋值
                commentVo1.setReplyUsername(commentVo2.getUserVo().getUsername());
            }
            //将第二层评论赋值
            commentVo.setCommentVoList(subCommentList);
        }


        return Result.success(commentVoList);
    }

    @Override
    public Result<String> deleteComment(Integer commentId) {

        List<Integer> commentIdList = new ArrayList<>();
        commentLikeService.remove(new QueryWrapper<CommentLike>().eq("comment_id",commentId));
        commentIdList.add(commentId);
        //删除后代id等于评论id的评论
        QueryWrapper<CommentRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq ("descendant", commentId);
        commentRelationService.remove(queryWrapper);

        //查找祖先id为评论id的后代
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq ("ancestor", commentId);
        List<CommentRelation> descendantList = commentRelationService.list(queryWrapper);

        //删除后代id等于评论id的后代id的评论
        for (CommentRelation commentRelation : descendantList){
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq ("descendant", commentRelation.getDescendant());
            commentRelationService.remove(queryWrapper);
            commentLikeService.remove(new QueryWrapper<CommentLike>().eq("comment_id",commentRelation.getDescendant()));
            commentIdList.add(commentRelation.getDescendant());
        }

        commentService.removeBatchByIds(commentIdList);

        return Result.success("删除评论成功") ;
    }
}
